
import json
import re
from urllib.parse import urljoin
from datetime import datetime, timedelta
import subprocess
import sys  # 添加 sys 模块导入


def send_email_with_blat(subject: str, body: str):
    # Replace with your actual blat command and email details
    conf = get_notification_config()
    for item in conf["notifications"]:
        if item["type"] == "mail":
            program = item["blat"]
            to = item["to"]
            cc = item["cc"]
            pwd = item["pindex"]
            frm = item["from"]
            break
    print(f"邮件配置：to:{to}, cc:{cc}, frm:{frm}, pwd:{pwd}")
    # 将配置文件中的邮件地址替换为实际的邮件地址
    blat_command = [
        program,
        "-to", to,
        "-cc", cc,
        "-subject", subject,
        "-body", body,
        "-f", frm,
        "-p", pwd 
    ]
    try:
        result = subprocess.run(blat_command, check=True)
        print("邮件发送成功。")
    except subprocess.CalledProcessError as e:
        print(f"邮件发送失败: {e}")

    pass

# 写一个json配置函数，以网站为单位，每个网站的配置信息包括：ID 网站 标题 链接 时间，时间的格式为：2023-09-12 16:45，每次发送邮件前检查配置文件，如果发送过此文章更新的网站则不发送

def check_and_send_email(website_id: str, website_name: str, title: str, post_time: datetime, link: str):
    config_file = "config.json"
    config = {}
    try:
        with open(config_file, "r") as file:
            config = json.load(file)
    except FileNotFoundError:
        print(f"Config 文件不存在 {config_file}. 正在创建。")
        config = {"sent": []}
    except json.JSONDecodeError as e:
        print(f"解析Json时遇到错误 {config_file}: {e}")
        sys.exit(1)

    # Check if the website ID is already in the sent list
    found = False
    for item in config["sent"]:
        if isinstance(item, dict) and item["id"] == website_id:
            found = True
            # print(f"{item["link"]}\n{link}")
            if item["link"] != link:
                send_and_update_config(website_id, website_name, title, post_time, link, config, config_file)
                return
            break

    if not found:
        send_and_update_config(website_id, website_name, title, post_time, link, config, config_file)


def send_and_update_config(website_id: str, website_name: str, title: str, post_time: datetime, link: str, config: dict, config_file: str):
    current_time = datetime.now()
    if website_id=='drc':
        subject = f"{website_name}在{current_time.strftime('%Y-%m-%d %H:%M')}更新了动态"
        body = f"{website_name}在{current_time.strftime('%Y-%m-%d %H:%M')}更新了动态：\n该文章编辑时间为：{post_time.strftime('%Y-%m-%d %H:%M')}\n标题：{title}\n链接：{link}"
    else:
        subject = f"{website_name}在{current_time.strftime('%Y-%m-%d %H:%M')}更新了大头条"
        body = f"{website_name}大头条已更新。更新时间：{current_time.strftime('%Y-%m-%d %H:%M')}\n编辑时间为：{post_time.strftime('%Y-%m-%d %H:%M')}\n标题：{title}\n链接：{link}"
    send_email_with_blat(subject, body)
    # 此处不要添加，修改已有的网站名称，否则会重复发送邮件
    # 检查是否已经存在相同的链接
    found = False
    for item in config["sent"]:
        if item["id"] == website_id:
            item["title"] = title
            item["time"] = post_time.strftime("%Y-%m-%d %H:%M")
            item["link"] = link  # 确保链接是绝对地址
            item["publishdate"]=current_time.strftime("%Y-%m-%d %H:%M")
            found = True
            break

    if not found:
        config["sent"].append({
            "id": website_id, 
            "title": title, 
            "time": post_time.strftime("%Y-%m-%d %H:%M"), 
            "website_name": website_name,  # 添加网站名
            "link": link,  # 确保链接是绝对地址
            "publishdate":current_time.strftime("%Y-%m-%d %H:%M")
        })
    with open(config_file, "w") as file:
        json.dump(config, file, indent=4)
        print(f"Email sent for {website_name} at {post_time.strftime('%Y-%m-%d %H:%M')}.")

    # 增加记录日志
    log_file = "log.txt"
    log_entry = f"{current_time.strftime('%Y-%m-%d %H:%M')}:  {website_name} 在{current_time.strftime('%Y-%m-%d %H:%M')}发布了新闻章：\n该文章编辑时间为：{post_time.strftime('%Y-%m-%d %H:%M')}\n标题：{title}\n链接：{link}\n\n"
    with open(log_file, "a") as file:
        file.write(log_entry)

#写一个notificationconfig.json文件，里面通知方式，程序名称，参数
def get_notification_config():
    notification_config_file = "notificationconfig.json"
    notification_config = {}
    try:
        with open(notification_config_file, "r") as file:
            notification_config = json.load(file)
    except FileNotFoundError:
        print(f"Notification Config 文件不存在 {notification_config_file}. 正在创建。")
        notification_config = {"notifications": []}
    except json.JSONDecodeError as e:
        print(f"解析Json时遇到错误 {notification_config_file}: {e}")
        sys.exit(1)
    return notification_config




